#!/usr/bin/env bash

##### My (demuredemeanor) cron_key script
# The purpose of this script is to provide an easy wrapper for cron scripts
# to be able to use your ssh-agent's stored key or gpg auth key.
# This is assuming that your key is already sourced like:
# https://notabug.org/demure/dotfiles/src/master/subbash/sshagent
# https://notabug.org/demure/dotfiles/src/master/subbash/sshgpgagent
#
# Uses tabstop=4; shiftwidth=4 tabs; foldmarker={{{,}}};
# https://notabug.org/demure/scripts

## Started by daemoneye
# https://github.com/kwolter/home_scripts/blob/master/ssh_key_fix.sh


SSH_ENV="${HOME}/.ssh/environment"
WRAPPED="$@"

SSH_FAIL=0      ## Initialize
GPG_FAIL=0      ## Initialize


## Check that augment is given, exit for non for help
if [ $# -eq 0 ] || [ $1 = "-h" ] || [ $1 = "--help" ]; then
    echo "Useage: $0 \"<command_to_run>\""
    exit 1
fi


## Test if ssh environment exists
if [ -s "${SSH_ENV}" ]; then
    . "${SSH_ENV}" > /dev/null ## Source ssh env
    ps "${SSH_AGENT_PID}" > /dev/null || SSH_FAIL=1     ## Make sure pid is good
  else
    SSH_FAIL=1
fi


## Assume that GPG is only desired if SSH key fails
if [ "${SSH_FAIL}" -eq 1 ]; then
    ## Test if a gpg auth key is in the key ring
    if [ "$(gpg -K | awk 'BEGIN {AK=0} /^ssb>?\s/ {if($4=="[A]"){AK=1}} END {print AK}')" -eq 1 ]; then
        ## Test that a gpg key is in cache (presumably you only have one keyring)
        GPG_CACHE="$({ gpg-connect-agent 'keyinfo --list' /bye 2>/dev/null; gpg-connect-agent 'scd getinfo card_list' /bye 2>/dev/null; } | awk 'BEGIN{CH=0} /^S/ {if($7==1){CH=1}; if($2=="SERIALNO"){CH=1}} END{if($0!=""){print CH} else {print "none"}}')"
        if [ "${GPG_CACHE}" -eq 1 ]; then
            unset SSH_AGENT_PID
            export SSH_AUTH_SOCK="$(gpgconf --list-dirs agent-ssh-socket)"
          else
            GPG_FAIL=1
        fi
      else
        GPG_FAIL=1
    fi
fi


## If both fail, print error and exit
if [ "${SSH_FAIL}" -eq 1 ] && [ "${GPG_FAIL}" -eq 1 ]; then
    echo "SSH key and GPG key failures."
    exit 1
fi


## Run passed command and exit
exec ${WRAPPED}
exit 0
